import { Component, Type, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STChange, STColumn, STComponent, STData } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Service } from '@api';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { SimpleActionField } from '@api/simple/model/simpleActionField.model';

@Component({
  template: '',
})
export abstract class SListComponent<T, ID> {
  isGeneralQuery = true;
  selectedRows: STData[] = [];
  ifvars: any = {
    isBatchOperate: false,
  };
  keyword: string = '';
  isUILoad = false;
  isDataLoad = false;

  url = '';
  searchSchema: SFSchema = {};

  toolbars: SimpleActionField[] = [];

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [];

  constructor(
    public http: _HttpClient,
    public modal: ModalHelper,
    public service: Service<T, ID>,
    public msgSrv: NzMessageService,
    public editComponent: Type<NzSafeAny>,
  ) {
    this.url = service.listUrl;
  }

  ngOnInit() {}

  action(name: string, argumentsList?: ArrayLike<any>) {
    if (!name) {
      return;
    }
    if (!argumentsList) {
      argumentsList = [];
    }
    const method = Reflect.getPrototypeOf(this) as any;
    return Reflect.apply(method[name], this, argumentsList);
  }

  delete(record: T | any, _modal: any, comp: any) {
    this.service.deleteById(record.id).subscribe((res) => {
      this.msgSrv.success(`成功删除`);
      this.st.reload();
    });
  }

  add() {
    this.modal.createStatic(this.editComponent, { i: {} }).subscribe(() => this.st.reload());
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        this.ifvars.isBatchOperate = this.selectedRows.length > 0;
        break;
    }
  }

  deletes() {
    const ids = this.selectedRows.map((row) => {
      return row.id;
    });
    this.service.deleteByIds(ids).subscribe((res) => {
      this.msgSrv.success(`成功删除`);
      this.st.reload();
    });
  }

  exportExcel() {
    this.st.export(true);
  }
}
